<?php
namespace app\Model;


class User extends Model
{
	private $id;
	private $email;
	private $userName;
	private $password;
	private $pwdConfirm;

	protected $dataDirectory = 'user';

	/**
	*根据数组中的数据，先验证数据，验证通过则返回User对象实例
	*/
	public static function newUser(Array $data)
	{
		$pwdConfirm = isset($data['pwdConfirm']) ? $data['pwdConfirm'] : '';
		$result = self::validate($data['id'], $data['email'], $data['userName'], $data['password'], $pwdConfirm);
			
		if ($result) {
			
			return self::fromArray($data);
		}
		return null;
	}

	public function albums()
	{
		return Album::get(['user.id' => $this->id]);
	}

	public static function fromArray(Array $array)
	{
		
		if (empty($array) || count($array) == 0) {
			return null;
		}

		$user = new User();
		$user->id = $array['id'];
		$user->email = $array['email'];
		$user->userName = $array['userName'];
		$user->password = $array['password'];
		return $user;
	}

	public function toArray()
	{
		return [
			'id' => $this->id,
		    'email' => $this->email,
		    'userName' => $this->userName,
		    'password' => $this->password
		];
	}

	/**
	*验证用户信息的数据有效性，使用静态方法
	*静态方法：不能通过对象实例调用，只能通过类名::调用
	*例如 self::validate(), User::validate()
	*静态方法：不能调用实例特性，只能访问静态特征
	*
	*@return mixed 验证通过，返回true，否则返回false
	*/
	private static function validate($id, $email, $userName, $password, $pwdConfirm)
	{
		$isValid = true;

		$errorBag = [
			'id' => '',
			'email' => '',
			'userName' => '',
			'password' => '',
			'pwdConfirm' => ''
		];

		$inputBag = [
			'id' => $id,
			'email' => $email,
			'userName' => $userName,
			'password' => $password
		];

		if (!preg_match('/^[1-9]+\d*$/', $id)) {
			$isValid = false;
			$errorBag['id'] = 'id只能是正整数';
		}
		if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
			$isValid = false;
			$errorBag['email'] = '邮箱地址不合法';
		}
		if (!preg_match('/^[\w\x{4e00}-\x{9fa5}]+$/u', $userName)) {
			$isValid = false;
			$errorBag['userName'] = '用户名不合法';
		}
		if (strlen($password) < 6) {
			$isValid = false;
			$errorBag['password'] = '密码不能小于6位';
		}
		if ($pwdConfirm !== $password) {
			$isValid = false;
			$errorBag['pwdConfirm'] = '两次输入密码必须一致';
		}

		if (session_status() != PHP_SESSION_ACTIVE) {
			session_start();
		}

		$_SESSION['errorBag'] = $errorBag;
		$_SESSION['inputBag'] = $inputBag;

		return $isValid;
	}


	public function __get($name)
	{
		if (property_exists(self::class, $name)) {
			return $this->$name;
		}
	}

	public function __set($name, $value) {
		if (property_exists(self::class, $name)) {
			$this->$name = $value;
		}
	}

	public function __toString() {
		return 'id: ' . $this->id . ' email: ' . $this->email . ' username: ' . $this->userName . '<br/>';
	}
}